import { getuserlist, getusercount } from '../../../request/api'
interface adminState {
  adminlist: Array<Object>
}

const state = {
  adminlist: [],
  pagesize: 2, //一页数据
  pagenum: 1, //当前页码
  count: 0 //总条数
}

const getters = {
  getAdmin(state: adminState) {
    return state.adminlist
  },
  //派发一页数据
  getSize(state: any) {
    return state.pagesize
  },
  //派发总数据
  getCount(state: any) {
    return state.count
  }
}

const mutations = {
  REQ_ADMIN(state: adminState, payload: any) {
    state.adminlist = payload
  },
  REQ_COUNT(state: any, payload: any) {
    state.count = payload
  },
  REQ_PAGENUM(state: any, payload: any) {
    state.pagenum = payload
  }
}

const actions = {
  getadminAction(context: any) {
    getuserlist({
      size: context.state.pagesize,
      page: context.state.pagenum
    }).then((res: any) => {
      let list = res.list ? res.list : []
      if (context.state.pagenum != 1 && list.length == 0) {
        //重新触发页码修改
        context.dispatch('changePageAction', context.state.pagenum - 1)
      }
      context.commit('REQ_ADMIN', res.list)
    })
  },
  getCountAction({ commit }: any) {
    getusercount().then((res: any) => {
      commit('REQ_COUNT', res.list[0].total)
    })
  },
  changePageAction(context: any, payload: any) {
    context.commit('REQ_PAGENUM', payload)
    context.dispatch('getadminAction')
  }
}

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced: true
}